require('../components/ali-oos/hmac.js');
require('../components/ali-oos/sha1.js');
const env = require('../components/ali-oos/config.js');
const base64 = require('../components/ali-oos/base64.js');
const Crypto = require('../components/ali-oos/crypto.js');
var getPolicyBase64 = function() {
	let date = new Date();
	date.setHours(date.getHours() + env.timeout);
	let srcT = date.toISOString();
	const policyText = {
		"expiration": srcT,
		"conditions": [
			["content-length-range", 0, 50 * 1024 * 1024] //上传容量最大为50M
		]
	};
	const policyBase64 = base64.encode(JSON.stringify(policyText));
	return policyBase64;
};
var getSignature = function(policyBase64) {
	const accesskey = env.AccessKeySecret;
	const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
		asBytes: true
	});
	const signature = Crypto.util.bytesToBase64(bytes);
	return signature;
};
var uploadFile = function(fileKey,imgurl) {
	return new Promise((resolve, reject) => {
		var _policy = getPolicyBase64();
		var _signature = getSignature(_policy);
		// console.log(_policy);
		// console.log(_signature);
		// console.log(fileKey);
		// console.log(imgurl);
		uni.uploadFile({
			url: env.fileHost,
			filePath: imgurl,
			name: 'file',
			formData: {
				'key': fileKey,
				'policy': _policy,
				'OSSAccessKeyId': env.OSSAccessKeyId,
				'signature': _signature,
				'success_action_status': '200'
			},
			success(res) {
				// console.log(res);
				resolve(res);
			},
			fail(err) {
				// console.log(err);
				reject(err);
			}
		});
	});
};
module.exports = {
	uploadFile,uploadFile
}
